package com.xored.searchwt;

import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.ViewPart;


/**
 * @author Yuri Strot
 *
 */
public class SearchView extends ViewPart implements ISearchView {
	
	public static final String ID = "com.xored.qsearch.view";
	
	private SearchControl control = new SearchControl();
	
	public static SearchView openView() throws PartInitException {
		IWorkbenchPage page = PlatformUI.getWorkbench().
			getActiveWorkbenchWindow().getActivePage();
		SearchView view = (SearchView)page.showView(SearchView.ID);
		return view;
	}
	
	public static void closeView() throws PartInitException {
		IWorkbenchPage page = PlatformUI.getWorkbench().
			getActiveWorkbenchWindow().getActivePage();
		SearchView view = (SearchView)page.findView(SearchView.ID);
		if (view != null)
			page.hideView(view);
	}
	
	public void update(IWorkbenchPart part, boolean highlight, String text) {
		control.update(part, highlight, text);
	}
	
	public void updateHighlightCount(int count) {
		control.updateHighlightCount(count);
	}
	
	public IWorkbenchWindow getWindow() {
		return getSite().getWorkbenchWindow();
	}
	
	public void backFocus() {
		try {
			closeView();
		} catch (PartInitException e) {
			e.printStackTrace();
		}
	}
	
	public Shell getShell() {
		return getSite().getShell();
	}
	
	public void acticate() {
		control.acticate();
	}
	
	public void initTextLayout(Composite parent, Control text) {
		text.setLayoutData(new GridData(100, -1));
	}
	
	public void initLabelLayout(Composite parent, Control label) {
	}
	
	/* (non-Javadoc)
	 * @see com.xored.qsearch.view.ISearchView#ignore(org.eclipse.ui.IWorkbenchPart)
	 */
	public boolean ignore(IWorkbenchPart part) {
		return part == this;
	}

	/* (non-Javadoc)
	 * @see org.eclipse.ui.part.WorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite)
	 */
	public void createPartControl(Composite parent) {
		GridLayout layout = new GridLayout(10, false);
		layout.horizontalSpacing = 0;
		layout.verticalSpacing = 0;
		layout.marginHeight = 2;
		layout.marginWidth = 2;
		parent.setLayout(layout);
		
		control.create(parent);
		control.initAgent(this);
	}

	/* (non-Javadoc)
	 * @see org.eclipse.ui.part.WorkbenchPart#setFocus()
	 */
	public void setFocus() {
		control.setFocus();
	}
	
	/* (non-Javadoc)
	 * @see org.eclipse.ui.part.WorkbenchPart#dispose()
	 */
	public void dispose() {
		control.dispose();
		control = null;
	}

}
